﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace XHouse.SerialPortManager
{
    using System.IO.Ports;

    /// <summary>
    /// Clase que maneja el controlador 18 
    /// </summary>
    public class Manager
    {
        /// <summary>
        /// The _rx string.
        /// </summary>
        public string _rxString;

        SerialPort serialPort1 = new SerialPort();

        public Manager()
        {
            serialPort1.DataReceived += this.serialPort1_DataReceived;
            this.Start();
        }

        private void Start()
        {

            var flag = false;
            int i = 1;
            while (!flag && i < 20)
            {
                try
                {
                    serialPort1.Close();
                    System.Threading.Thread.Sleep(500);
                    serialPort1.PortName = "COM" + i.ToString();
                    //labelPort.Text = "Traying Opening Port" + serialPort1.PortName;
                    serialPort1.BaudRate = 9600;
                    i++;
                    serialPort1.Open();
                    if (serialPort1.IsOpen)
                    {
                        flag = Comprobar18();
                    }
                }
                catch (System.IO.IOException exception)
                {
                 //   labelPort.Text = exception.Message;
                }
            }

            //labelPort.Text = "Port Detected: " + serialPort1.PortName + " BaudRate: " + serialPort1.BaudRate + "Por Open: " + serialPort1.IsOpen;

            //buttonStart.Enabled = false;
            //buttonStop.Enabled = true;
            //textBox1.ReadOnly = false;


        }

        private bool Comprobar18()
        {
            // If the port is closed, don't try to send a character.

            if (!serialPort1.IsOpen) return false;

            // If the port is Open, declare a char[] array with one element.
            char[] buff = new char[12];
            byte[] mBuffer = new byte[6];
            mBuffer[0] = 0xaa;
            mBuffer[1] = 0xab;
            mBuffer[2] = 0x11;
            mBuffer[3] = 0x22;
            mBuffer[4] = 0x33;
            mBuffer[5] = 0xee;
            serialPort1.Write(mBuffer, 0, mBuffer.Length);

            // Load element 0 with the key character.



            // Send the one character buffer.
            //serialPort1.Write(buff, 0, 1);

            System.Threading.Thread.Sleep(500);

            return !String.IsNullOrEmpty(this._rxString);
        }

        private void Stop(object sender, EventArgs e)
        {
            //labelPort.Text = "Port is Closed";
            if (serialPort1.IsOpen)
            {
                serialPort1.Close();
                //buttonStart.Enabled = true;
                //buttonStop.Enabled = false;
                //textBox1.ReadOnly = true;
            }

            //buttonStart.Enabled = true;

        }

        private void DisplayText()
        {
            //textBox1.Text = "";
            //textBox2.AppendText(RxString + "\r\n");

            this._rxString = "";

        }

        private void serialPort1_DataReceived
          (object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            byte[] bufferReader = new byte[6];
            this._rxString = "";
            if (serialPort1.IsOpen)
            {

               this._rxString = serialPort1.ReadExisting();

               this.DisplayText();
            }

        }



        /// <summary> Convert a string of hex digits (ex: E4 CA B2) to a byte array. </summary>
        /// <param name="s"> The string containing the hex digits (with or without spaces). </param>
        /// <returns> Returns an array of bytes. </returns>
        private byte[] HexStringToByteArray(string s)
        {
            s = s.Replace(" ", "");
            byte[] buffer = new byte[s.Length / 2];
            for (int i = 0; i < s.Length; i += 2)
                buffer[i / 2] = (byte)Convert.ToByte(s.Substring(i, 2), 16);
            return buffer;
        }

    }
}
